package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccFbaDeliver;
import com.ys.entity.storage.TccFbaDeliverItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.storage.TccFbaDeliverService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.RedisUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-30
 * @Description: FBA发货单控制层
 * @Version: 1.5
 */
@Controller
@RequestMapping("/api/inter/tccFbaDeliver")
public class ApiInterTccFbaDeliverController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccFbaDeliverController.class);

    @Autowired
    private TccFbaDeliverService tccFbaDeliverService;

    @Autowired
    private CommonApiService<TccFbaDeliver> commonApiService;

    //菜单id
    private Long menuId = MenuId.TCC_FbaDeliver;
    private Long menuId1 = MenuId.TCC_FbaDeliverX;
    private Long menuId2 = MenuId.TCC_FbaDeliverWc;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccFbaDeliver:view";
    private final String PERMISSIONS_DEL = "tccFbaDeliver:del";
    private final String PERMISSIONS_PRINTING = "tccFbaDeliver:printing";
    private final String PERMISSIONS_FLOW = "tccFbaDeliver:flow";
    private final String PERMISSIONS_EXPORT = "tccFbaDeliver:exportWc";
    private final String PERMISSIONS_WLXG = "tccFbaDeliver:wlxg";
    private final String PERMISSIONS_WLXGWC = "tccFbaDeliver:wlxgWc";


    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccFbaDeliver setSeachSql(TccFbaDeliver cond){

        cond.addLeftJoin("TCC_FbaDeliverItem B ON B.Pbid = A.Bid ")
                .addField("B.boxNo")//箱号
                .addField("B.auditingTime")//审核时间
                .addField("B.auditingUser")//审核人
            .addLeftJoin("TCC_FbaBoxDetail C ON C.id = B.FbaBoxDetailId ")
                .addField("C.num")//箱中数量
                .addField("C.purchaseAmount priceIn")//商品采购价
            .addLeftJoin("TCC_FbaBox D ON D.id = C.BoxId ")
                .addField("(CONVERT(varchar(10), cast(D.BoxLong as float)) + '*' + CONVERT(varchar(10), cast(D.BoxWide as float))  + '*' + CONVERT(varchar(10), cast(D.BoxHigh as float))) dimensionsCase")//箱尺寸
                .addField("D.boxWeight")//箱重量
            .addLeftJoin("TCC_FbaBoxUpInfo E ON E.BoxUpBid = C.BidBoxUp ")
                .addField("E.boxUpBid")//FBA装箱单号
                .addField("E.fbaNo")//FBA编号
                .addField("E.fbaTrackNo")//FBA追踪编号
                .addField("E.fbaToken")//FbaToken
                .addField("E.fbaId")//FbaId
                .addField("E.fbaWarehouse")//FBA仓库
                .addField("E.fbaWarehouseAddr")//FBA仓库地址
//                .addField("E.packToken")//包装组Token
//                .addField("E.packId")//包装组Id
                .addField("E.fbaAmount")//Fba费用
                .addField("E.boxUpNum")//装箱数量
            .addLeftJoin("TCC_FbaBoxUp F ON F.bid = E.BoxUpBid ")
                .addField("F.distributionBid")//配货清单号
            .addLeftJoin("TCC_FbaFeeDetails G ON G.sourceBid = F.bid AND G.sourceType = 1")
                .addField("G.priceTranPredict boxPriceTranPredict")//实际物流费（总）
            .addLeftJoin("TCC_FbaBoxUpItem H ON H.id = C.BoxUpItemId ")
                .addField("H.AverageBoxUpNum averageBoxNum")
            .addLeftJoin("TCC_FbaPlanItem I ON I.id = H.FbaPlanItemId")
                .addField("I.commodityCode,I.commodityName,I.sku,I.numStock,I.numPlanDeliver,I.isSign,I.signCode,I.annexFile,I.asin,I.fnSku,I.codeGoodsHs,I.nameGoodsCn")
                .addField("I.nameMaterialCn,I.weightPackage,I.vck,I.vkq,I.vhw")
                .addField("(CONVERT(varchar(19), cast(I.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(I.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(I.heightPackage as float))) packageSize")
            .addLeftJoin("TCC_FbaPlan J ON J.bid= I.bidFbaPlan ")
                .addField("J.bid fbaplanBid")//FBA计划单号
                .addField("J.creationMethod")//下单方式
                .addField("J.declarationState")//是否报关
                .addField("J.deliverState")//发货计划
                .addField("J.vgsbm")//运营公司编码
                .addField("J.vgsJc")//运营公司简称
                .addField("J.shopName")//网店名称
                .addField("J.remark")//FBA计划单备注
            .addLeftJoin("TCC_FbaLogisticsMethod K ON K.sourceBid = A.bid AND K.sourceType = 1")
                .addField("K.logsticsWay")//物流方式
            .addLeftJoin("TCC_FbaFeeDetails L ON L.sourceBid = J.bid AND L.sourceType = 0")
                .addField("L.priceTranPredict")//预估物流费（总）
            .addLeftJoin("TS_UserChange U ON U.Id = J.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUser")//制单人
                .setOrderby("A.Bid DESC");//排序

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccFbaDeliver cond, String conditions){
        cond = setSeachSql(cond);
        cond.where("A.Status < 2");
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchWc")
    @ResponseBody
    public LayuiTableVoJA searchWc(@ModelAttribute TccFbaDeliver cond, String conditions){
        cond = setSeachSql(cond);
        cond.where("A.Status >= 2");
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /**
     * 箱标打印
     */
    @RequiresPermissions(PERMISSIONS_PRINTING)
    @RequestMapping("/printing")
    @ResponseBody
    public R printing(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            return tccFbaDeliverService.printing(params);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("箱标打印出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 计划取消
     */
    @RequiresPermissions(PERMISSIONS_DEL)
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(HttpServletRequest request, Long id,int type){
        try {
            return tccFbaDeliverService.delete(id,type);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("计划取消出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 转运审核
     */
    @RequiresPermissions(PERMISSIONS_FLOW)
    @RequestMapping("/flow")
    @ResponseBody
    public R flow(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            return tccFbaDeliverService.flow(params);
        } catch (Exception e) {
            logger.error("转运审核出错：",e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getMessage());
        }
    }

    /*
     * 导出
     */
    @RequiresPermissions(PERMISSIONS_EXPORT)
    @RequestMapping("/exportWc")
    @ResponseBody
    public R exportWc(@ModelAttribute TccFbaDeliver cond, String conditions) throws Exception{
        cond.setOrderby("A.Id DESC");
        cond = setSeachSqlNew(cond);
        String _ys_status = ConditionUtil.getConditionValue(conditions, "_ys_status");//货件状态
        if (_ys_status != null && _ys_status.length() > 0){
            if (!_ys_status.equals("6")){
                cond.where("A.status = " + _ys_status);
            }
        }else {
            cond.where("A.status != 3");
        }
        cond.addField("CASE WHEN A.status = 2  THEN '已转运' WHEN A.status = 3  THEN '已取消' WHEN A.status = 4  THEN '待发货'  ELSE '已发货' END  statusName");
        cond.addField("CASE WHEN J.creationMethod = 0  THEN '手动'   ELSE '自动' END  creationMethodName");
        cond.addField("CASE WHEN J.EffectStock = 0  THEN '未生效'   WHEN J.EffectStock = 1  THEN '已生效'  ELSE '已作废' END  effectStockName");
        cond.addField("CASE WHEN J.deliverState = 0  THEN '按箱自动发货'  ELSE '按SKU自动发货' END  deliverStateName");
        cond .addField("case when J.declarationState = 0 then '否' else '是' end as declarationStateName");
        cond.setPage(0).setSize(999999);

        List<Map<String, Object>> listData = cond.queryMap();

        List<YsCol> listField = new YsCol()
                .setMenuId(menuId2)
                .setFrontExport(YsColEnum.FrontExport.SHOW.value)
                .setOrderby("A.SortNo asc")
                .queryList();


        ExportExcelUtils<TccFbaDeliver> util = new ExportExcelUtils<TccFbaDeliver>(new TccFbaDeliver());

        String toFilePath = util.exportExcel(listData, listField, "FBA完成单");
        UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccFbaDeliver setSeachSqlNew(TccFbaDeliver cond){

        cond
                .addLeftJoin("TCC_FbaDeliverItem B ON B.Pbid = A.bid ")
                .addField("B.fbaBoxUpInfoId")
                .addField("B.apiTrackStatus")//api是否上传追踪编号
                .addLeftJoin("TCC_FbaBoxUpInfo E ON E.id = B.FbaBoxUpInfoId")
                .addField("E.boxUpBid")//FBA装箱单号
                .addField("E.fbaNo")//FBA编号
                .addField("E.fbaTrackNo")//FBA追踪编号
                .addField("E.fbaToken")//FbaToken
                .addField("E.fbaId")//FbaId
                .addField("E.fbaWarehouse")//FBA仓库
                .addField("E.fbaWarehouseAddr")//FBA仓库地址
                .addField("E.fbaAmount")//Fba费用
                .addLeftJoin("TCC_FbaBoxUp F ON F.bid = E.BoxUpBid ")
                .addField("F.packToken")//包装组Token
                .addField("F.packId")//包装组Id
                .addField("F.distributionBid")//配货清单号
                .addLeftJoin("TCC_FbaFeeDetails G ON G.sourceBid = A.bid AND G.sourceType = 1")
                .addField("G.priceTranPredict boxPriceTranPredict")//实际物流费（总）
                .addLeftJoin("TCC_FbaPlan J ON J.bid= A.FbaPlanBid ")
                .addField("J.bid fbaplanBid")//FBA计划单号
                .addField("J.shopId shopId")//店铺信息
                .addField("J.creationMethod")//下单方式
                .addField("J.declarationState")//是否报关
                .addField("J.deliverState")//发货计划
                .addField("J.vgsbm")//运营公司编码
                .addField("J.vgsJc")//运营公司简称
                .addField("J.shopName")//网店名称
                .addField("J.remark")//FBA计划单备注
                .addField("J.evenlyBoxNum")//均分箱数
                .addLeftJoin("TCC_FbaLogisticsMethod K ON K.sourceBid = A.bid AND K.sourceType = 1")
                .addField("K.logsticsWay")//物流方式
                .addLeftJoin("TCC_FbaFeeDetails L ON L.sourceBid = J.bid AND L.sourceType = 0")
                .addField("L.priceTranPredict")//预估物流费（总）
                .addLeftJoin("TS_UserChange U ON U.Id = J.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUser")//制单人
                .addLeftJoin("TCC_LogisticsSadFile lsf ON lsf.fbaNo = E.fbaNo ")
                .addField("lsf.annexFile annexFile")
                .addField("lsf.id sourceId")
                .addLeftJoin("TCC_LogisticsComprehensive tlc ON tlc.fbaNo = E.fbaNo AND tlc.Status = 1")
                .addField("tlc.trackingCode trackingCode")
                .addField("tlc.orderGenTime orderGenTime")
                .addField("A.status _ys_status")
                .addField("(SELECT COUNT(1) FROM (SELECT BoxId FROM TCC_FbaBoxDetail WHERE FbaBoxUpInfoId = E.id GROUP BY BoxId) A) boxNum")
                .setOrderby("A.Bid DESC");//排序

        cond = commonApiService.dataAuth(menuId1, cond);
        return  cond;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchNew")
    @ResponseBody
    public LayuiTableVoJA searchNew(@ModelAttribute TccFbaDeliver cond, String conditions){
        cond = setSeachSqlNew(cond);
        cond.where("A.Status < 2");
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchWcNew")
    @ResponseBody
    public LayuiTableVoJA searchWcNew(@ModelAttribute TccFbaDeliver cond, String conditions){
        cond = setSeachSqlNew(cond);
        cond.where("A.Status >= 2");
        String _ys_status = ConditionUtil.getConditionValue(conditions, "_ys_status");//货件状态
        if (_ys_status != null && _ys_status.length() > 0){
            if (!_ys_status.equals("6")){
                cond.where("A.status = " + _ys_status);
            }
        }else {
            cond.where("A.status != 3");
        }
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchZb")
    @ResponseBody
    public LayuiTableVoJA searchZb(@ModelAttribute TccFbaDeliver cond, String rowConditions){
        TccFbaDeliver tccFbaDeliver = JSON.parseObject(rowConditions, TccFbaDeliver.class);
        TccFbaDeliverItem tccFbaDeliverItem = JSON.parseObject(rowConditions, TccFbaDeliverItem.class);
        cond.addLeftJoin("TCC_FbaDeliverSon B ON B.Pbid = A.Bid ")
                .addField("B.boxNo")//箱号
                .addLeftJoin("TCC_FbaDeliverItem DD ON DD.id = B.FbaDeliverItemId ")
                .addLeftJoin("TCC_FbaBox D ON D.id = B.FbaBoxId ")
                .addField("(CONVERT(varchar(10), cast(D.BoxLong as float)) + '*' + CONVERT(varchar(10), cast(D.BoxWide as float))  + '*' + CONVERT(varchar(10), cast(D.BoxHigh as float))) dimensionsCase")//箱尺寸
                .addField("D.boxWeight")//箱重量
                .addField("D.BoxNo AS boxNoNum")//装箱编号
                .addLeftJoin("TCC_FbaBoxDetail C ON C.BoxId = D.id ")
                .addField("C.num")//箱中数量
                .addField("C.purchaseAmount priceIn")//商品采购价
                .addLeftJoin("TCC_FbaBoxUpItem H ON H.id = C.BoxUpItemId ")
                .addField("H.AverageBoxUpNum averageBoxNum")
                .addField("H.goodsLink goodsLink")
                .addField("H.averageBoxUpNum averageBoxUpNum")
                .addLeftJoin("TCC_FbaPlanItem I ON I.id = H.FbaPlanItemId")
                .addField("I.commodityCode,I.commodityName,I.sku,I.numStock,I.numPlanDeliver,I.isSign,I.signCode,I.annexFile,I.asin,I.fnSku,I.codeGoodsHs,I.nameGoodsCn")
                .addField("I.nameMaterialCn,I.weightPackage,I.vck,I.vkq,I.vhw,I.numApiDeliver")
                .addField("(CONVERT(varchar(19), cast(I.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(I.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(I.heightPackage as float))) packageSize")
                .setOrderby("A.Bid DESC,B.boxNo");//排序
        if (tccFbaDeliver != null) {
            cond.where("DD.FbaBoxUpInfoId = " + tccFbaDeliverItem.getFbaBoxUpInfoId());
        }
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /**
     * 物流服务名称修改(完成单)
     */
    @RequiresPermissions(PERMISSIONS_WLXGWC)
    @PostMapping("/editLogisticsMethodWc")
    @ResponseBody
    public R editLogisticsMethodWc(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("bid"))){
                return R.error("单号为空");
            }
            if(checkUtil.isNullByObject(params.get("logisticsMethodId"))){
                return R.error("物流服务参数有误");
            }
            String bid = params.get("bid").toString();
            if(redisUtil.get("WLBG-" + bid)!= null && !"".equals("WLBG-" + bid)){
                return R.error("1分钟内不允许重复点击");
            }
            redisUtil.setEx("WLBG-" + bid,"0",1, TimeUnit.MINUTES);//设置过期时间
            Integer isType = null;
            if (params.get("isType") != null && !params.get("isType").equals("")){
                isType = new Integer((params.get("isType").toString()));
            }
            R r = tccFbaDeliverService.editLogisticsMethodId(bid,Long.parseLong(params.get("logisticsMethodId").toString()),isType,1);
            if (r.getCode() != 0 || r.getMsg().contains("该货件不满足物流服务最小发货重量")){
                redisUtil.delete("WLBG-" + bid);
                return r;
            }
            r = tccFbaDeliverService.recalculateFlow(bid);
            if (r.getCode() != 0){
                redisUtil.delete("WLBG-" + bid);
                return r;
            }

            return R.ok("物流服务变更成功!");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 物流服务名称修改
     */
    @RequiresPermissions(PERMISSIONS_WLXG)
    @PostMapping("/editLogisticsMethod")
    @ResponseBody
    public R editLogisticsMethod(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            if(checkUtil.isNullByObject(params.get("bid"))){
                return R.error("单号为空");
            }
            if(checkUtil.isNullByObject(params.get("logisticsMethodId"))){
                return R.error("物流服务参数有误");
            }
            Integer isType = null;
            if (params.get("isType") != null && !params.get("isType").equals("")){
                isType = new Integer((params.get("isType").toString()));
            }
            return tccFbaDeliverService.editLogisticsMethodId(params.get("bid").toString(),Long.parseLong(params.get("logisticsMethodId").toString()),isType,0);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }
}
